import { fetchGetUserInfoApi, fetchLoginApi } from '@/api'
import { ElMessage } from 'element-plus'
import { defineStore } from 'pinia'

export const useUserInfoStore = defineStore('useUserInfo', {
  state: (): UseUserInfoType => ({
    // 用户信息
    username: '',
    avatar: '',
    // 用户token
    token: localStorage.getItem('token') || ''
  }),
  actions: {
    /**
     * 设置token
     */
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
    },
    /**
     * 设置用户信息
     */
    setUserInfo(userInfo: any) {
      this.username = userInfo.username
      this.avatar = userInfo.avatar
    },
    /**
     * 用户登录
     * @params {string} username 用户名
     * @params {string} password 密码
     */
    async userLogin(loginForm: { username: string; password: string }) {
      await fetchLoginApi(loginForm).then(res => {
        if (res.code === 200) {
          ElMessage.success(res.message)
          this.setToken(res.data.token)
          this.getUserInfo()
        }
      })
    },
    /**
     * 获取用户信息
     */
    async getUserInfo() {
      await fetchGetUserInfoApi().then(res => {
        if (res.code === 200) {
          this.setUserInfo(res.data)
        }
      })
    },
    /**
     * 退出登录
     */
    userLoginOut() {
      this.setToken('')
      this.setUserInfo({})
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      ElMessage.success('退出成功')
    }
  }
})
